#include "mytcpserver.h"
#include <QDebug>

MyTcpServer::MyTcpServer()
{

}

MyTcpServer &MyTcpServer::getInstance()
{
    static MyTcpServer instance;
    return instance;
}

void MyTcpServer::incomingConnection(qintptr socketDescriptor)
{
    // 一个连接对应一个文件描述符，用于区分不同的连接
    qDebug() << "new client connected";
    MyTcpSocket *pTcpSocket = new MyTcpSocket;
    pTcpSocket->setSocketDescriptor(socketDescriptor);
    m_tcpSocketList.append(pTcpSocket);

    connect(pTcpSocket,SIGNAL(offline(MyTcpSocket*)),this,SLOT(deleteSocket(MyTcpSocket*)));
}

void MyTcpServer::resend(const char *pername, PDU *pdu)
{
    if(NULL == pername || NULL == pdu) {
        return;
    }
    QString strName = pername;

    for(int i = 0; i < m_tcpSocketList.size(); i++) {
        if(strName == m_tcpSocketList.at(i)->getName()) {
            m_tcpSocketList.at(i)->write((char*)pdu, pdu->uiPDULen);
            break;
        }
    }
}

void MyTcpServer::handleAddFriendResponse(PDU *pdu)
{
    char caPerName[32] = {'\0'};
    char caName[32] = {'\0'};
    strncpy(caPerName, pdu->caData,32); // 被申请人
    strncpy(caName,pdu->caData+32,32); // 申请人

    if(pdu->uiMsgType == ENUM_MSG_TYPE_ADD_FRIEND_AGREE) {
        for(int i = 0; i < m_tcpSocketList.size(); i++) {
            if(caName == m_tcpSocketList.at(i)->getName()) {
                pdu->uiMsgType = ENUM_MSG_TYPE_ADD_FRIEND_AGREE_RESPONSE;
                // 执行入库操作
                bool ret = OpeDB::getInstance().addFriendPersistence(caPerName,caName);
                if(ret) {
                    m_tcpSocketList.at(i)->write((char*)pdu, pdu->uiPDULen);
                }else {
                    QString errMsg = QString("%1 添加 %2 好友入库失败").arg(caName).arg(caPerName);
                    qDebug() << errMsg;
                }
                break;
            }
        }
    } else if(pdu->uiMsgType == ENUM_MSG_TYPE_ADD_FRIEND_REFUSE) {
        for(int i = 0; i < m_tcpSocketList.size(); i++) {
            if(caName == m_tcpSocketList.at(i)->getName()) {
                pdu->uiMsgType = ENUM_MSG_TYPE_ADD_FRIEND_REFUSE_RESPONSE;
                m_tcpSocketList.at(i)->write((char*)pdu, pdu->uiPDULen);
                break;
            }
        }
    }
}

void MyTcpServer::deleteSocket(MyTcpSocket *mysocket)
{
    QList<MyTcpSocket*>::Iterator iter = m_tcpSocketList.begin();
    for(; iter != m_tcpSocketList.end(); iter++) {
        if(mysocket == *iter) {
            delete *iter;
            *iter = NULL;
            m_tcpSocketList.erase(iter);
            break;
        }
    }

    for(int i=0; i<m_tcpSocketList.size(); i++) {
        qDebug() << m_tcpSocketList.at(i)->getName();
    }
}
